﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.CMS.Workflow;
using MethodWorx.Core.DomainModel;
using MethodWorx.CMS.Services;

namespace MethodWorx.CMS.TemplateParser.Installer.Components
{
    public class MasterPageTemplate : IInstallationWorkflowComponent
    {

        public StepExecutionResult Execute(IWorkflowExecutionContext context, InstallerWorkflowComponentConfiguration configuration)
        {
            var variables = context.GetAllWorkflowValues();
            var name = configuration.ConfigurationElement.GetAttributeValue("name", null, true, variables);
            var description = configuration.ConfigurationElement.GetAttributeValue("description", "", true, variables);
            var content = configuration.ConfigurationElement.GetAttributeValue("content", null, true, variables);

            if(string.IsNullOrEmpty(name))
                return StepExecutionResult.Error("Missing name attribute");

            if (string.IsNullOrEmpty(content))
                return StepExecutionResult.Error("Missing content attribute");

            if (!configuration.Files.Keys.Contains(content.ToLower()))
                return StepExecutionResult.Error("Missing installation file:" + content);

            var templateText = System.Text.ASCIIEncoding.ASCII.GetString(configuration.GetParsedFileContents(content.ToLower(), variables));

            //
            //  ok, simple enough here
            //  we want to load the template file
            using(var uow = context.CmsDataProvider.GetUnitOfWorkFactory().Begin())
            {
                var service = new SchemaService(context.CmsDataProvider);
                //  create the page template
                var template= service.CreatePageTemplate(name, description, false, null, true);
                service.SaveTemplate(template, templateText);
                    
                //  commit the unit of work
                uow.Commit();   
            }

            return StepExecutionResult.Ok();
        }
    }
}
